package com.whately.core.base.export.msexcel;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.whately.core.base.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zjx
 * @date 2020/4/20
 **/
@Slf4j
public class ExportExcelUtils {
    /**
     * @param contentList 导出内容
     * @param response
     * @param excelName   文件名
     */
    public static void exportExcel(List<?> contentList,
                                   HttpServletResponse response,
                                   String excelName) {

        List<Object> rows = new ArrayList<>(contentList);

        ExcelWriter writer = ExcelUtil.getWriter(true);

        //写入到excel
        writer.write(rows);
        try {
            //vnd.ms-excel  03版
            //vnd.openxmlformats-officedocument.spreadsheetml.sheet   07版
            String fileName = URLEncoder.encode(excelName + ".xlsx", "UTF-8");
            OutputStream outputStream = response.getOutputStream();
            //response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + fileName);

            //浏览器只识别：小写
            String attachFileNameInHeader = "attachfilename";

            response.setHeader(attachFileNameInHeader, fileName);
            response.setHeader("Access-Control-Expose-Headers", attachFileNameInHeader);
            writer.flush(outputStream, true);
            outputStream.flush();

            outputStream.close();
        } catch (IOException e) {
            //e.printStackTrace();
            log.error("exportExcel error", e);
            throw new ServiceException(400, "导出失败！" + e.getMessage());
        } finally {
            writer.close();
        }

    }
}
